#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
清理fund_info和fund_info_detail表数据的脚本
"""

import os
import sys
import django  # type: ignore

# 设置Django环境
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, current_dir)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wealth_backend.settings_mysql')
django.setup()

from data_service.models import FundInfo, FundInfoDetail

def clear_fund_tables():
    """
    清理fund_info和fund_info_detail表中的所有数据
    """
    try:
        # 查询清理前的数据量
        fund_info_count = FundInfo.objects.count()
        fund_info_detail_count = FundInfoDetail.objects.count()
        
        print(f"清理前数据统计:")
        print(f"  fund_info表: {fund_info_count} 条记录")
        print(f"  fund_info_detail表: {fund_info_detail_count} 条记录")
        
        if fund_info_count == 0 and fund_info_detail_count == 0:
            print("\n表中没有数据，无需清理")
            return
        
        # 确认清理操作
        confirm = input(f"\n确认要清理所有数据吗？这将删除 {fund_info_count + fund_info_detail_count} 条记录 (y/N): ")
        if confirm.lower() != 'y':
            print("操作已取消")
            return
        
        print("\n开始清理数据...")
        
        # 清理fund_info_detail表（先清理子表）
        if fund_info_detail_count > 0:
            print(f"正在清理fund_info_detail表的 {fund_info_detail_count} 条记录...")
            deleted_detail = FundInfoDetail.objects.all().delete()
            print(f"已删除fund_info_detail表 {deleted_detail[0]} 条记录")
        
        # 清理fund_info表
        if fund_info_count > 0:
            print(f"正在清理fund_info表的 {fund_info_count} 条记录...")
            deleted_info = FundInfo.objects.all().delete()
            print(f"已删除fund_info表 {deleted_info[0]} 条记录")
        
        # 验证清理结果
        final_info_count = FundInfo.objects.count()
        final_detail_count = FundInfoDetail.objects.count()
        
        print(f"\n清理完成！")
        print(f"清理后数据统计:")
        print(f"  fund_info表: {final_info_count} 条记录")
        print(f"  fund_info_detail表: {final_detail_count} 条记录")
        
        if final_info_count == 0 and final_detail_count == 0:
            print("\n✅ 所有数据已成功清理")
        else:
            print("\n⚠️ 警告：部分数据可能未被清理")
            
    except Exception as e:
        print(f"清理数据时发生错误: {str(e)}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    clear_fund_tables()